package com.kang.common.comm;

import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    public static final String DATE_FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT = "yyyy-MM-dd";
    public static final String DATE_DAY_FORMAT = "MMdd";
    public static final String TIME_ZONE_SH = "Asia/Shanghai";

    /**
     * 根据日期对象转字符串
     * @param date
     * @return
     */
    public static String dateTimeToStr(Date date){
        if(date == null){
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_DEFAULT);
        return sdf.format(date);
    }

    /**
     * 根据日期对象转字符串yyyy-MM-dd格式
     * @param date
     * @return
     */
    public static String dateToStr(Date date){
        if(date == null){
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        return sdf.format(date);
    }

    /**
     * 根据日期对象和格式转字符串
     * @param date
     * @return
     */
    public static String dateDayToStr(Date date, String formatStr){
        if(date == null || StringUtils.isBlank(formatStr)){
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
        return sdf.format(date);
    }

    /**
     * 获取前一天的yyyy-MM-dd，带时区
     * @param date
     * @param zoneId
     * @param days
     * @return
     */
    public static Date getDayBefore(Date date, String zoneId, int days){
        if(date == null || StringUtils.isBlank(zoneId)){
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        LocalDateTime time1 = LocalDateTime.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH)+1, calendar.get(Calendar.DAY_OF_MONTH),0,0,0);

        LocalDateTime time2 = time1.minusDays(days);
        ZoneId zone = ZoneId.of(zoneId);
        Instant instant = time2.atZone(zone).toInstant();
        Date newDate = Date.from(instant);
        return newDate;
    }

}
